<?php

class Resource_Backend_Action_Inline_Edit extends Resource_Backend_Action_Common_Edit 
{
    
    /**
     * Initialize form elements. 
     *
     */
    protected function _initElements() 
    {
        parent::_initElements();
        
        $this->_addElement('position', array(
               'type' => 'list', 
             'values' => $this->_positions(Resource_Backend_Utils::position_max($this->navigation)), 
              'value' => Resource_Backend_Utils::position($this->navigation, 0, $this->id), 
            ));
        
        $this->_setAsRequired('position', 'name');
        $this->_setElementPosition('position', 4);
        
        // add hidden fields for ajax request 
        $this->_addElement('menu_name', 'hidden', array('value' => $this->navigation));
        $this->_addElement('resource', 'hidden', array('value' => Resource_Backend::active()));
    }
    
    /**
    * Return positions list. Return max + 1 additional position in case of:
    * - navigation is tree or 
    * - navigation inline but action ADD
    * 
    * @return array
    */
    protected function _positions($max_pos) 
    {
        if ('add' == Application::getRequest()->get('action')) {
            $max_pos += 1;
        }
        
        return $this->_positionsCombine($max_pos);
    }
    
    protected function _positionsCombine($number) 
    {
        $positions = range(1,  $number);
        return array_combine($positions, $positions);
    }
    
    protected function _insert() 
    {
        parent::_insert();
        
        $this->_addNode();
    }
    
    protected function _update() 
    {
        // update `system_resource`
        parent::_update();
        
        $this->_moveNode();
    }
    
    /**
    * Return params for current node type
    * 
    * @return array
    */
    protected function _params() 
    {
        return array(
            'table' => 'system_navigation_item', 
            'id_field' => 'resource_id', 
            'condition' => array('menu_id' => Resource_Backend_Utils::menuId($this->navigation))
            );
    }
    
    /**
    * Add element into stack on position specified.
    * 
    */
    private function _addNode() 
    {
        Kernel::factory('Kernel_Form', 'Order', $this->_params())
            ->addNode($this->_getValue('position'), array(
                'menu_id' => Resource_Backend_Utils::menuId($this->navigation), 
                'resource_id' => $this->id, 
                ));
    }
    
    /**
    * Move element through the stack `system_navigation_item`
    * 
    * @param array $params
    */
    private function _moveNode() 
    {
        Kernel::factory('Kernel_Form', 'Order', $this->_params())
            ->moveNode($this->id, $this->_getValue('position'));
    }
    
}